<!--
 * @Descripttion: 加工单
 * @version: V1.0
 * @Author: GaoWei
 * @Date: 2021-06-28 11:53:39
 * @LastEditors: GW
 * @LastEditTime: 2022-01-29 17:52:12
-->
<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper">
            <!-- 按钮 -->
            <div class="btn-wrapper clearfix">
                <btns-wrapper @searchClick="searchClick" :showModel="showModel" :orderId="orderId" :voucherState="voucherState" :editMask="editMask" @printOrder="printOrder" @switchList="switchList" @submitServer="submitServer" @clickEdit="clickEdit" @deleteOrder="deleteOrder" @getIdByData="getIdByData" @auditClick="auditClick" @turnThePage="turnThePage" @syncOrder="syncOrder" @submitOrder="submitOrder" @exportDetail="exportDetail" :sourceCode="sourceCode">
                    <template slot="neworder">
                        <a-dropdown class="btns" key="new" style="display:block">
                            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增
                                    <a-icon type="down" style="color:rgb(24,144,255);vertical-align:middle;" />
                                </div>
                            </a>
                            <a-menu slot="overlay">
                                <a-menu-item key="0">
                                    <a href="javascript:void(0)" @click="newForecast">新增</a>
                                </a-menu-item>
                                <a-menu-item key="1">
                                    <a href="javascript:void(0)" @click="choiceBillsFromProductionOrder">选计划订单</a>
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </template>
                    <!-- <template slot="shengdan">
                        <div class="btns-disable">
                            <a-dropdown class="btns" key="sheng" style="display:block">
                                <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                    <a-icon class="btns-icon" type="snippets" />
                                    <div class="btns-text">生单
                                        <a-icon type="down" />
                                    </div>
                                </a>
                                <a-menu v-if="voucherState==1" slot="overlay">
                                    <a-menu-item key="0">
                                        <a href="javascript:void(0)" @click="generateBills('MaterialDispatchVoucher')">生成委外领料单</a>
                                    </a-menu-item>
                                </a-menu>

                            </a-dropdown>
                        </div>
                    </template> -->
                </btns-wrapper>
            </div>
            <div ref="print" class="documents-wrapper" id="documents-wrapper">
                <h3 class="text-center">
                    {{voucherTitle}}
                </h3>
                <section v-show="showModel=='list'">
                    <dynamicList ref="dyList" :basePostData="basePostData" :sourceCode="sourceCode" :dataSourceCode="dataSourceCode" @switchList="switchList" @dblclick="getIdByData" :reportCode="reportCodeList"></dynamicList>
                </section>
                <section v-show="showModel=='order'">
                    <div><span class="audit-status" v-show="voucherState==0">待审核</span><span class="audit-status" v-show="voucherState==1 || voucherState==10">{{voucherState==1?'已审核':'关闭'}}</span></div>
                    <a-form-model :layout="formLayout">
                        <div class="header-box">
                            <order-dynamic-form :FormData="orderHeaderData" @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                            <div class="edit-mask-header" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                        <div class="table-box">
                            <!-- :rowClassName="rowClassNameWork" -->
                            <a-table id="bills_tb" :columns="columns" :data-source="dataSource" :customRow="customClick" :scroll="{ x: 1000, y: 347 }" :pagination="false" @change="onTableChange" :size="small" bordered>
                                <template v-if="isRouterAlive" slot="number" slot-scope="text, record, index">
                                    <div v-if="index == dataSource.length-1">
                                         合计
                                    </div>
                                    <div v-else>
                                        {{index+1}}
                                    </div>
                                </template>
                                <template v-for="col in slotArray" :slot="col" slot-scope="text, record,index">
                                    <div data-key="">
                                        <editable-cell v-if="isRouterAlive" :checkType="checkType" :text="text" :col="col" :index="index" :record="record" :dataSource="dataSource" :unitsDataDetails="unitsDataDetails" :unitsAssistSelect="unitsAssistSelect" :dynamicAllData="dynamicFormData" :dynamicFormDataMap="dynamicFormDataMap"  @choiceAddData="choiceAddData(index,col,$event)" @change="onCellChange(index, col, $event)" @newAddData="handleAdd" />
                                    </div>
                                </template>
                            </a-table>
                            <!-- 遮罩（点击修改关闭遮罩） -->
                            <!-- <div class="edit-mask" style="height:calc(100% - 66px)" v-show="editMask">   

                            </div> -->
                        </div>

                        <div class="footer-box">
                            <order-dynamic-form :FormData="orderFooterData"  @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                            <div class="edit-mask-footer" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                        <br />
                        <a-tabs default-active-key="1" @change="callback">
                            <a-tab-pane key="1" tab="物料明细" style="position:relative">
                                <div class="wuliao-mask" v-show="editMask">

                                </div>
                                <a-table :columns="columnsBom" :dataSource="dataSourceBom" :customRow="customClickMin" :pagination="false" style="min-height:300px;" :scroll="{ x: 1800, y: 347 }" bordered>
                                    <!--发料方式-->
                                    <template slot="deliveryMethod" slot-scope="text">
                                        <div>{{ text == 1?'直接领料':text == 2?'调拨领料':text==3?'直接倒冲':text==4?'调拨倒冲':text==5?'不发料':'' }}</div>
                                    </template>
                                    <!--供应类型-->
                                    <template slot="supplyType" slot-scope="text">
                                        <div>{{ text == 1?'采购':text == 2?'自制':text==3?'委外':'' }}</div>
                                    </template>
                                    <template v-for="item in editColumnBom" :slot="item" slot-scope="text, record ,index">
                                        <div>

                                            <!-- <editable-cell v-if="isRouterAliveWork" :text="text" :col="item" :index="index" :record="record" :dataSource="dataSourceBom" :unitsDataDetails="unitsDataDetails" :unitsAssistSelect="unitsAssistSelect" :dynamicAllData="dynamicFormData" :dynamicFormDataMap="dynamicFormDataMap"  @choiceAddData="choiceAddData(index,col,$event)" @change="onCellChangeMinBom(index, item, $event)" @newAddData="handleAdd" /> -->
                                            <editable-cell-min v-if="isRouterAliveWork" :checkType="minCheckType" :record="record" :col="item" :unitsDataDetails="unitsDataDetails" :unitsAssistSelect="unitsAssistSelect" :text="text" @change="onCellChangeMinBom(index, item, $event)" />
                                        </div>
                                    </template>

                                    <template slot="number" v-if="isRouterAliveWork" slot-scope="text, record, index">
                                        <div>
                                            {{index+1}}
                                        </div>
                                    </template>
                                    <!--需要数量-->
                                    <!-- <template slot="requireQuantity" v-if="isRouterAliveWork" slot-scope="text">
                                        <div style="text-align:right;padding-right:2px;">
                                            {{text | NumFormat}}
                                        </div>
                                    </template> -->
                                </a-table>
                            </a-tab-pane>
                            <a-tab-pane key="2" tab="工序明细" force-render>
                                <a-table :columns="columnsRoute" :dataSource="dataSourceRoute" :pagination="false" style="min-height:300px;" :scroll="{ x: 1000, y: 347 }" bordered>
                                    <template slot="number" v-if="isRouterAliveWork" slot-scope="text, record, index">
                                        <div>
                                            {{index+1}}
                                        </div>
                                    </template>
                                    <!--加工方式-->
                                    <template slot="processMethod" slot-scope="value">
                                        <div>
                                            {{ value == 1?'自制加工':value == 2?'委外加工':'' }}
                                        </div>
                                    </template>
                                    <!--工序标识-->
                                    <template slot="workFlag" slot-scope="value">
                                        <div>
                                            {{ value == 1?'首工序':value == 2?'尾工序':value==3?'中间工序':'' }}
                                        </div>
                                    </template>
                                    <!--检验方式-->
                                    <template slot="inspectMethod" slot-scope="value">
                                        <div>
                                            {{ value == 1?'免检':value == 2?'过程检验':value==3?'完工检验':'' }}
                                        </div>
                                    </template>
                                    <template v-for="item in editColumnRoute" :slot="item" slot-scope="text, record ,index">
                                        <div>
                                            <editable-cell-min v-if="isRouterAliveWork" :record="record" :col="item" :text="text" @change="onCellChangeMinRoute(index, item, $event)" />
                                        </div>
                                    </template>
                                </a-table>
                            </a-tab-pane>

                        </a-tabs>
                    </a-form-model>
                    
                </section>
                <section v-show="showModel=='detail'">
                    <!--明细-->
                    <dynamicListDetails ref="detailSearchRef" :reportCode="reportCodeDetail" :dataSourceCode="dataSourceCode" :componentType="1" :basePostData="basePostData"></dynamicListDetails>
                </section>
                <section v-show="showModel=='statistical'">
                    <!--统计-->
                    <dynamicListDetails ref="statisticalSearchRef" :reportCode="reportCodeStatistical" :dataSourceCode="dataSourceCode" :componentType="2" :basePostData="basePostData"></dynamicListDetails>
                </section>
            </div>
            <div class="contextmenu-box">
                <!-- 右键菜单 -->
                <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
                    <li @click="handleAdd()">新增行</li>
                    <li @click="handleDelete()">删除行</li>
                    <!-- <li @click="handleCopy()">复制行</li> -->
                </ul>
                <!-- 明细 -->
                <ul v-show="visibleDetails" :style="{left:leftDetails+'px',top:topDetails+'px'}" class="contextmenu">
                    <li @click="handleAddDetails()">新增行</li>
                    <li @click="handleDeleteDetails()">删除行</li>
                    <!-- <li @click="handleCopy()">复制行</li> -->
                </ul>
            </div>
            <drawerBox ref="searchList" :unitData="unitData" :unitsData="unitsData" :unitsDataDetails="unitsDataDetails" @editClickOrder="editClickOrder"></drawerBox>
        </div>

        <!--加载中-->
        <div class="loading-wrapper" v-show="loading">
            <a-spin class="loading-content" tip="加载中..." />
        </div>
        <!--用做横向打印-->
        <!-- <div v-html="stylePrint"></div> -->
        <print-modal ref="printDom" v-if="printVisible" :incomingPrintData="incomingPrintData" @cancelPrint="cancelPrint"></print-modal>

    </div>
</template>
<script>


import { save, examine, remove, getCode, getIdDetails, getBomDetails, getClDetails, submitOrder } from '@/api/production/productionWork'

import { details } from "@/api/production/bom";
import { details as detailsRoute } from "@/api/production/processRoute";

import pro from '@/mixins/procurement/pro'
import editableCellMin from "../production/workshop/editTable/EditableCell"
import { clearValue, clearKeys } from "@/utils/tool/object";

import { IdFieldToNameField } from "@/utils/customize";
//物料明细
export default {
    mixins: [pro],
    components: {
        editableCellMin
    },
    data () {
        return {
            //基础 查询条件（列表 + 翻页）
            basePostData: {
                dataSource: 'ProductionWork',
            },
            sourceCode: 'ProductionWork',
            reportCodeDetail: 'ProductionWork_Detail_Report',
            reportCodeStatistical: 'ProductionWork_Statistic_Report',   //统计code
            reportCodeList: 'ProductionWork_List_Report',            //列表code
            dataSourceCode: 'ProductionWork',//区分委外
            checkType: 'is_made_self',//自制
            minCheckType:'is_material',    //是否生产耗用
            // isProductionWork: true,     //是否是加工单
            // productionWorkDataMain: [],  //当前页所有数据集合

            columnsBom: [
                {
                    title: 'bom版本',
                    dataIndex: 'bomName',
                    width: 80,
                }, {
                    title: '物料编码',
                    dataIndex: 'inventoryCode',
                    scopedSlots: { customRender: 'inventoryCode' },
                    width: 120,
                }, {
                    title: '物料名称',
                    dataIndex: 'inventoryName',
                    scopedSlots: { customRender: 'inventoryName' },
                    width: 120,
                }, {
                    title: '规格型号',
                    dataIndex: 'inventorySpecification',
                    scopedSlots: { customRender: 'inventorySpecification' },
                    width: 120,
                }, {
                    title: '主计量',
                    dataIndex: 'baseUnitName',
                    scopedSlots: { customRender: 'baseUnitName' },
                    width: 60,
                }, {
                    title: '辅计量',
                    dataIndex: 'subUnitName',
                    scopedSlots: { customRender: 'subUnitName' },
                    width: 60,
                }, {
                    title: '换算率',
                    dataIndex: 'unitExchangeRate',
                    align: 'right',
                    // scopedSlots: { customRender: 'unitExchangeRate' }
                    width: 60,
                },
                {
                    title: '预出仓库',
                    dataIndex: 'warehouseName',
                    scopedSlots: { customRender: 'warehouseName' },
                    width: 120,
                },
                {
                    title: '需求基数',
                    dataIndex: 'baseRequireQuantity',
                    scopedSlots: { customRender: 'baseRequireQuantity' },
                    width: 80,
                },
                {
                    title: '计划数量',
                    dataIndex: 'plannedQuantity',
                    scopedSlots: { customRender: 'plannedQuantity' },
                    width: 80,
                }, {
                    title: '需要数量',
                    dataIndex: 'requireQuantity',
                    scopedSlots: { customRender: 'requireQuantity' },
                    width: 80,
                }, {
                    title: '损耗数量',
                    dataIndex: 'lossQuantity',
                    scopedSlots: { customRender: 'lossQuantity' },
                    width: 80,
                }, {
                    title: '损耗率(%)',
                    dataIndex: 'lossRate',
                    scopedSlots: { customRender: 'lossRate' },
                    width: 80,
                }, {
                    title: '计划数量（辅）',
                    dataIndex: 'subPlannedQuantity',
                    scopedSlots: { customRender: 'subPlannedQuantity' },
                    width: 80,
                }, {
                    title: '需要数量（辅）',
                    dataIndex: 'subRequireQuantity',
                    scopedSlots: { customRender: 'subRequireQuantity' },
                    width: 80,
                }, {
                    title: '损耗数量（辅）',
                    dataIndex: 'subLossQuantity',
                    scopedSlots: { customRender: 'subLossQuantity' },
                    width: 80,
                }, {
                    title: '可用量',
                    dataIndex: 'availableQuantity',
                    align: 'right',
                    width: 80,
                }, {
                    title: '现存量',
                    dataIndex: 'existingQuantity',
                    align: 'right',
                    width: 80,
                }],
            columnsRoute: [
                {
                    title: '序号',
                    dataIndex: 'number',
                    width: 40,
                    align: 'center',
                    scopedSlots: { customRender: 'number' },
                },
                {
                    title: '工序编码',
                    dataIndex: 'workCode',
                    width: 100,
                    ellipsis: true,
                },
                {
                    title: '工序名称',
                    dataIndex: 'procedureName',
                    width: 100,
                    ellipsis: true,
                },
                // {
                //     title: '工人名称',
                //     dataIndex: 'workerNames',
                //     scopedSlots: { customRender: 'workerName' },
                // }, {
                //     title: '班组',
                //     dataIndex: 'teamName',
                //     scopedSlots: { customRender: 'teamName' },
                // }, 
                {
                    title: '加工方式',
                    dataIndex: 'processMethod',
                    scopedSlots: { customRender: 'processMethod' },
                }, {
                    title: '工序标识',
                    dataIndex: 'workFlag',
                    scopedSlots: { customRender: 'workFlag' },
                }, {
                    title: '检验方式',
                    dataIndex: 'inspectMethod',
                    scopedSlots: { customRender: 'inspectMethod' },
                }, {
                    title: '质检标准',
                    dataIndex: 'qualityStandard',
                },
                {
                    title: '工艺要求',
                    dataIndex: 'processRequire',
                    width: 100,
                    ellipsis: true,
                },
                {
                    title: "开工日期",
                    align: 'left',
                    show: true,
                    dataIndex: "startDate",
                    scopedSlots: {
                        customRender: "startDate",
                    }
                },
                {
                    title: "完工日期",
                    align: 'center',
                    show: false,
                    dataIndex: "endDate",
                },
                {
                    title: "合格数量",
                    align: 'right',
                    show: false,
                    dataIndex: "cumQualifiedQuantity",
                    customRender: (text) => {
                        return this.$numberFormat(text);
                    }
                },
                {
                    title: "不合格数量",
                    align: 'right',
                    show: false,
                    dataIndex: "cumUnqualifiedQuantity",
                    customRender: (text) => {
                        return this.$numberFormat(text);
                    }
                },
                 {
                    title: "返工数量",
                    align: 'right',
                    show: false,
                    dataIndex: "cumReworkQuantity",
                    customRender: (text) => {
                        return this.$numberFormat(text);
                    }
                },
                {
                    title: '备注',
                    dataIndex: 'procedureRemark',
                    ellipsis: true,
                }],
            dataSourceBom: [],//bom数据
            dataSourceRoute: [],//工序数据
            isRouterAlive: true,
            isRouterAliveWork: true,
            editColumnBom: ['requireQuantity'],
            editColumnRoute: ['workerName', 'teamName'],

            currentRouteId: null,//当前工艺路线id
            currentBomId: null,  //当前bom id

            dataSourceBomNumber: 0,//用于主数据数量该变 触发watch监听物料明细数量的计算
            customClickMin: (record, index) => {
                return {
                    on: {
                        click: (e) => {
                            e.preventDefault();
                            if (record.unitGroupId) {
                                this.unitsAssistSelect = [];
                                this.unitsDataDetails.forEach((element, index) => {
                                    if (element.unitGroupId == record.unitGroupId && !element.isMainUnit) {//&& !element.isMainUnit
                                        this.unitsAssistSelect.push(element);
                                    }
                                });
                            } else {
                                this.unitsAssistSelect = [];
                            }
                        },
                        contextmenu: (e) => {//右键事件
                            e.preventDefault();
                            this.openMenuDetails(e);
                            console.log('右键点击的', index, e);
                            this.thisClickIdDetails = index;
                        },
                    }
                }
            },
            visibleDetails: false,//明细右键
            leftDetails: 0,
            topDetails: 0,
            dataSourceNumberOther: 12,
            thisClickIdDetails: null,
            arrs:[],//生产计划获取的数据
            id:0,
            dataSource:[]
        };
    },
    created () {
        //this.getIdByData();//获取最新一条数据
    },
    mounted () {
        this.editColumnBom = [];
        setTimeout(() => {
            this.columnsBom.forEach(item => {
                if (item.scopedSlots && item.scopedSlots.customRender) {
                    this.editColumnBom.push(item.scopedSlots.customRender);
                }
            });
        }, 200)
        this.id=this.$route.query.id;
        this.arrs=JSON.parse(this.$route.query.arrs)
        console.log(this.id,'ids')
    },
    watch: {
        dataSourceBomNumber (val) {
            console.log('dataSourceBomNumber物料明细数据改变——————,', this.dataSourceBom, val);
            //plannedQuantity:计划数量 requireQuantity：需要数量 lossQuantity：损耗数量  lossRate：损耗率
            this.dataSourceBom.forEach(item => {
                // if (item.bomId == this.currentBomId) {
                if (item.lossRate != null && item.requireQuantity != null) {

                    //计划数量=需要数量 + 需要数量*损耗率
                    item.plannedQuantity = (Number(item.requireQuantity) + Number(item.requireQuantity) * (item.lossRate / 100)).toFixed(4);

                    //损耗数量=计划数量-需要数量
                    item.lossQuantity = (Number(item.plannedQuantity) - Number(item.requireQuantity)).toFixed(4);

                    if (item.subUnitName) {
                        //辅计量计划数量
                        item.subPlannedQuantity = (Number(item.plannedQuantity) / Number(item.unitExchangeRate)).toFixed(4);
                        console.log(item.plannedQuantity, item.unitExchangeRate, item.subPlannedQuantity);
                        //辅计量需要数量
                        item.subRequireQuantity = (Number(item.requireQuantity) / Number(item.unitExchangeRate)).toFixed(4);
                        //辅计量损耗数量
                        item.subLossQuantity = (Number(item.subPlannedQuantity) - Number(item.subRequireQuantity)).toFixed(4);

                    }

                } else {
                    if (item.requireQuantity != null && item.lossQuantity != null) {
                        //计算 计划数量=需要数量+损耗数量
                        item.plannedQuantity = (Number(item.requireQuantity) + Number(item.lossQuantity)).toFixed(4);
                    }

                    if (item.plannedQuantity != null && item.requireQuantity != null) {
                        //计算 损耗数量=计划数量-需要数量
                        item.lossQuantity = (Number(item.plannedQuantity) - Number(item.requireQuantity)).toFixed(4);
                    }

                    if (item.lossQuantity != null && item.requireQuantity != null) {
                        //计算  损耗率=（损耗数量/需要数量）*100
                        let losstate = (Number(item.lossQuantity) / Number(item.requireQuantity)).toFixed(4) * 100;
                        item.lossRate = losstate.toFixed(4);
                    }
                }
                // }
            })
            this.reloadWork();
        },
        visibleDetails (value) {
            if (value) {
                document.body.addEventListener("click", this.closeMenuDetails);
            } else {
                document.body.removeEventListener("click", this.closeMenuDetails);
            }
        },
        dataSourceBom: {
            handler (newData, oldData) {
                this.dataSource.forEach((res, index) => {
                    if (index == this.classWorkCurrent) {
                        res.productionWorkInventoryDetailList = newData;
                        this.reloadWork();
                    }
                })
            },
            deep: true
        },
        dataSourceRoute: {
            handler (newData, oldData) {
                this.dataSource.forEach((res, index) => {
                    if (index == this.classWorkCurrent) {
                        res.productionWorkProcedureDetailList = newData;
                        this.reloadWork();
                    }
                })
            },
            deep: true
        }
    },
    computed: {
        // dataSourceBom: {
        //     get: function (value) {
        //         console.log('dataSourcre:', value)
        //     },
        //     set: function (value) {
        //         this.dataSourceBom = value; //最后修改了msg    
        //     }
        // }
    },
    methods: {

        //补足表格
        supplementTable () {
            if (this.dataSourceBom.length < this.dataSourceNumber) {
                for (let i = this.dataSourceBom.length; i < this.dataSourceNumber; i++) {
                    let array = {};
                    this.dataSourceBom.push(array);
                }
            }
        },
        rowClassNameWork (record, index) {
            return this.classWorkCurrent == index ? 'hoverWorkStyle' : '';
        },
        //新增预测单
        newForecast () {
            this.showModel = 'order';
            this.editMask = false;
            this.loading = false;
            this.voucherState = -1;
            this.sourceVoucherData = {};//清空来源数据
            this.dataSourceBom = [];
            this.supplementTable();
            this.dataSourceRoute = [];
            this.initForm(1);
            this.reloadWork();
        },
        //保存
        submit (requestData) {
            let data = requestData.orderDetailList;
            data.forEach(element=>{
                if(element.sourceVoucherType == "主生产计划"){
                    element.sourceVoucherType = "MasterProductionSchedule"
                }
                if(element.sourceVoucherType == "物料需求计划"){
                    element.sourceVoucherType = "RequirementPlan"
                }
            })
            for (let index = 0; index < data.length; index++) {
                data[index].source = "ProductionWork"
                data[index].productionWorkInventoryDetailList = data[index].productionWorkInventoryDetailList.filter(s => s.inventoryId);
                let array = data[index].productionWorkInventoryDetailList;
                for (let i = 0; i < array.length; i++) {
                    if (array[i].plannedQuantity < array[i].requireQuantity) {
                        this.$message.warning('计划数量不能小于需要数量！')
                        this.isSaveRun = true;
                        return;
                    }
                }
            }
            console.log(requestData);
            save(requestData).then(response => {
                if (response.code === 200) {
                    this.$message.success('保存成功');
                    this.editMask = true;
                    this.isSaveRun = true;
                    if (!this.orderId) {
                        this.getIdByData(); //获取最新一条数据
                    }
                } else {
                    this.$message.error(response.message);
                    this.isSaveRun = true;
                }
            }).catch((e) => {
                this.isSaveRun = true;
            })
        },
        //单据提交
        submitOrder (type) {
            let data = {
                id: this.orderId,
                status: type,//状态 -1:撤回提交,0:提交
            }
            console.log(this.orderId);
            if (!this.orderId) {
                this.$message.warning('该单据未保存不需要提交');
                return;
            }
            if (this.voucherState == -1 && type == -1) {
                this.$message.warning('该单据未提交无需撤回提交');
                return;
            }
            submitOrder(data).then(res => {
                if (res.code === 200) {
                    if (type == 0) {
                        this.$message.success('提交成功');
                    } else {
                        this.$message.success('撤回提交成功');
                    }
                    this.getIdByData();
                }
            })
        },
        //审核
        auditClick (type) {
            let requestData = {
                id: this.orderId,
                status: type
            }
            examine(requestData).then((response) => {
                if (response.code === 200) {
                    const backData = response.data;
                    if (type == 1) {
                        this.$message.success('审核成功');
                        this.getIdByData();
                    }
                    if (type == 0) {
                        this.$message.success('弃审成功');
                        this.getIdByData();
                    }
                } else {
                    // this.$message.warning(response.message);
                }
            })
        },
        //删除
        remove (postData) {
            remove(postData).then(response => {
                if (response.code === 200) {
                    this.$message.success('删除成功');
                    this.orderId = '';
                    this.voucherState = 0;
                    this.getIdByData();//获取最新一条数据
                } else {
                    this.$message.error(response.message);
                }
            })
        },
        //获取单据编号
        getCode () {
            getCode().then((res) => {
                if (res.code == 200) {
                    this.receiptNumber = res.message;
                    for (let i = 0; i < this.orderHeaderData.length; i++) {
                        if (this.orderHeaderData[i].code == 'voucherCode') {
                            this.$set(this.orderHeaderData[i], 'onEdit', false)
                            this.$set(this.orderHeaderData[i], 'value', this.receiptNumber)
                        }
                    }
                } else {
                    // this.$message.warning(res.message);
                }
            });
        },
        //通过加委外加工单ID 获取加工单物料明细
        getClDetails (data) {
            let postData = { "productionWorkMainId": data.id };
            getClDetails(postData).then(response => {
                if (response.code === 200) {
                    this.dataSourceBom = response.data;
                } else {
                    this.$message.error(response.message);
                }
            }).catch((e) => { })
        },
        //展示工艺明细
        showDetailsRoute (record) {
            this.currentRouteId = record.processRouteId;
            if (record.productionWorkProcedureDetailList && record.productionWorkProcedureDetailList.length > 0) {
                this.dataSourceRoute = record.productionWorkProcedureDetailList;
            } else {
                this.dataSourceRoute = [];
            }
            console.log("展示工艺明细_数量：",this.dataSourceRoute.length);
            this.$nextTick(() => {
                this.reloadWork();
            })
        },
        //展示材料明细
        showBomDetails (record) {
            console.log('展示材料明细：', record)
            this.currentBomId = record.bomId;
            if (record.productionWorkInventoryDetailList && record.productionWorkInventoryDetailList.length > 0) {
                this.dataSourceBom = record.productionWorkInventoryDetailList;
            } else {
                this.dataSourceBom = [];
            }
            console.log('展示材料明细_数量：',this.dataSourceBom.length)
            this.$nextTick(() => {
                this.reloadWork();
                this.supplementTable();
            })

        },
        //获取bom材料明细
        getBomDetails (id, num, bomExpMethod) {
            let isSingle = false;   //BOM是否 单阶展开
            this.dataSourceBom = [];//清空物料明细
            if (bomExpMethod && 1 == bomExpMethod) isSingle = true;
            this.currentBomId = id;
            //获取尾阶bom材料明细
            getBomDetails({ 'motherBomId': id, isGetAvailableQuantity: true, isSingle }).then(response => {
                if (response.code === 200) {

                    // let tempData = [];//零时存储当前物料明细数据
                    // this.dataSource.forEach(aa => {
                    if (num && num != 0 && num != null) {
                        response.data.forEach(item => {
                            item.requireQuantity = (Number(num) * Number(item.baseRequireQuantity)).toFixed(4);//需要数量
                            // item.lossRate != null ? item.lossRate = item.lossRate.toFixed(4) : item.lossRate = '0.0000';
                            // item.lossQuantity != null ? item.lossQuantity = item.lossQuantity.toFixed(4) : item.lossQuantity = '0.0000';
                            // item.plannedQuantity = item.requireQuantity + Number(item.lossQuantity);//计划数量
                            if (item.lossRate != null && item.requireQuantity != null) {

                                //计划数量=需要数量 + 需要数量*损耗率
                                item.plannedQuantity = (Number(item.requireQuantity) + Number(item.requireQuantity) * (item.lossRate / 100)).toFixed(4);

                                //损耗数量=计划数量-需要数量
                                item.lossQuantity = (Number(item.plannedQuantity) - Number(item.requireQuantity)).toFixed(4);

                                if (item.subUnitName) {
                                    //辅计量计划数量
                                    item.subPlannedQuantity = (Number(item.plannedQuantity) / Number(item.unitExchangeRate)).toFixed(4);
                                    console.log(item.plannedQuantity, item.unitExchangeRate, item.subPlannedQuantity);
                                    //辅计量需要数量
                                    item.subRequireQuantity = (Number(item.requireQuantity) / Number(item.unitExchangeRate)).toFixed(4);
                                    //辅计量损耗数量
                                    item.subLossQuantity = (Number(item.subPlannedQuantity) - Number(item.subRequireQuantity)).toFixed(4);

                                }

                            } else {
                                if (item.requireQuantity != null && item.lossQuantity != null) {
                                    //计算 计划数量=需要数量+损耗数量
                                    item.plannedQuantity = (Number(item.requireQuantity) + Number(item.lossQuantity)).toFixed(4);
                                }

                                if (item.plannedQuantity != null && item.requireQuantity != null) {
                                    //计算 损耗数量=计划数量-需要数量
                                    item.lossQuantity = (Number(item.plannedQuantity) - Number(item.requireQuantity)).toFixed(4);
                                }

                                if (item.lossQuantity != null && item.requireQuantity != null) {
                                    //计算  损耗率=（损耗数量/需要数量）*100
                                    let losstate = (Number(item.lossQuantity) / Number(item.requireQuantity)) * 100;
                                    item.lossRate = losstate.toFixed(4);
                                }
                            }
                        })
                    }
                    // });
                    this.dataSourceBom = response.data;
                    this.$nextTick(() => {
                        this.supplementTable();
                        this.reloadWork();
                    })
                   
                } else {
                    this.$message.error(response.message);
                }
            }).catch((e) => { });
        
        },
        async getBomDetails2(id, num, bomExpMethod,detailRecord){
            return new Promise(function(resolve, reject) {
                let isSingle = false;   //BOM是否 单阶展开
                if (bomExpMethod && 1 == bomExpMethod) isSingle = true;
                //获取尾阶bom材料明细
                getBomDetails({ 'motherBomId': id, isGetAvailableQuantity: true, isSingle }).then(response => {
                    if (response.code === 200) {

                        // let tempData = [];//零时存储当前物料明细数据
                        // this.dataSource.forEach(aa => {
                        if (num && num != 0 && num != null) {
                            response.data.forEach(item => {
                                item.requireQuantity = (Number(num) * Number(item.baseRequireQuantity)).toFixed(4);//需要数量
                                // item.lossRate != null ? item.lossRate = item.lossRate.toFixed(4) : item.lossRate = '0.0000';
                                // item.lossQuantity != null ? item.lossQuantity = item.lossQuantity.toFixed(4) : item.lossQuantity = '0.0000';
                                // item.plannedQuantity = item.requireQuantity + Number(item.lossQuantity);//计划数量
                                if (item.lossRate != null && item.requireQuantity != null) {

                                    //计划数量=需要数量 + 需要数量*损耗率
                                    item.plannedQuantity = (Number(item.requireQuantity) + Number(item.requireQuantity) * (item.lossRate / 100)).toFixed(4);

                                    //损耗数量=计划数量-需要数量
                                    item.lossQuantity = (Number(item.plannedQuantity) - Number(item.requireQuantity)).toFixed(4);

                                    if (item.subUnitName) {
                                        //辅计量计划数量
                                        item.subPlannedQuantity = (Number(item.plannedQuantity) / Number(item.unitExchangeRate)).toFixed(4);
                                        console.log(item.plannedQuantity, item.unitExchangeRate, item.subPlannedQuantity);
                                        //辅计量需要数量
                                        item.subRequireQuantity = (Number(item.requireQuantity) / Number(item.unitExchangeRate)).toFixed(4);
                                        //辅计量损耗数量
                                        item.subLossQuantity = (Number(item.subPlannedQuantity) - Number(item.subRequireQuantity)).toFixed(4);

                                    }

                                } else {
                                    if (item.requireQuantity != null && item.lossQuantity != null) {
                                        //计算 计划数量=需要数量+损耗数量
                                        item.plannedQuantity = (Number(item.requireQuantity) + Number(item.lossQuantity)).toFixed(4);
                                    }

                                    if (item.plannedQuantity != null && item.requireQuantity != null) {
                                        //计算 损耗数量=计划数量-需要数量
                                        item.lossQuantity = (Number(item.plannedQuantity) - Number(item.requireQuantity)).toFixed(4);
                                    }

                                    if (item.lossQuantity != null && item.requireQuantity != null) {
                                        //计算  损耗率=（损耗数量/需要数量）*100
                                        let losstate = (Number(item.lossQuantity) / Number(item.requireQuantity)) * 100;
                                        item.lossRate = losstate.toFixed(4);
                                    }
                                }
                            })
                        }
                        if(detailRecord){
                            detailRecord.productionWorkInventoryDetailList = response.data;
                        }
                        resolve();
                    } else {
                       
                    }
                }).catch((e) => { reject(); });
            });
        },
        //获取工艺路线
        getRouteDetails (id) {
            this.currentRouteId = id;
            detailsRoute({ 'id': id }).then(response => {
                if (response.code === 200) {
                    this.dataSourceRoute = response.data;

                    this.dataSourceRoute.forEach(item => {
                        item.procedureId = item.workId;//工序id
                        item.procedureCode = item.workCode;//工序编码
                        item.procedureName = item.workName;//工序名称
                        item.processRouteDetailId = item.id;//工艺路线_工序明细

                        item.processSort = item.workFlag;//工序标识
                        item.procedureRemark = item.remarks;//工序备注
                        delete item.id;
                    });
                    this.$nextTick(() => {
                        this.reloadWork();
                    })
                } else {
                    this.$message.error(response.message);
                }
            }).catch((e) => { })
        },
        //获取工艺路线
        async getRouteDetails2 (id,detailRecord) {
             return new Promise(function(resolve, reject) {
                 detailsRoute({ id }).then(response => {
                    if (response.code === 200) {
                        detailRecord.productionWorkProcedureDetailList = response.data;
                        detailRecord.productionWorkProcedureDetailList.forEach(item => {
                            item.procedureId = item.workId;//工序id
                            item.procedureCode = item.workCode;//工序编码
                            item.procedureName = item.workName;//工序名称
                            item.processRouteDetailId = item.id;//工艺路线_工序明细

                            item.processSort = item.workFlag;//工序标识
                            item.procedureRemark = item.remarks;//工序备注
                            delete item.id;
                        });
                        resolve();
                    } 
                }).catch((e) => { reject(); });
            });
           
        },
        //物料明细表单修改回调处理
        onCellChangeMinBom (indexTable, dataIndex, value) {
            console.log(indexTable, dataIndex, value, this.dataSourceBom)
            const dataSourceBom = [...this.dataSourceBom];
            const target = dataSourceBom.find((item, index) => index === indexTable);
            if (dataIndex == 'warehouseName') {
                //仓库
                if (value) {
                    target['warehouseName'] = value.whName;
                    target['warehouseId'] = value.id;
                } else {
                    target['warehouseName'] = null;
                    target['warehouseId'] = null;
                }
            } else if (dataIndex == 'plannedQuantity') {
                if (!target.requireQuantity || target.requireQuantity == null || target.requireQuantity == 0) {
                    this.$message.warning('请填写需要数量！');
                    return;
                }

                if (!target.baseRequireQuantity || target.baseRequireQuantity == null || target.baseRequireQuantity == 0) {
                    this.$message.warning('请填写需求基数！');
                    return;
                }
                //计划数量 
                this.$set(target, dataIndex, value);
                if (target.plannedQuantity != null && target.requireQuantity != null) {
                    //计算 损耗数量=计划数量-需要数量
                    target.lossQuantity = (Number(target.plannedQuantity) - Number(target.requireQuantity)).toFixed(4);
                }

                if (target.lossQuantity != null && target.requireQuantity != null) {
                    //计算  损耗率=（损耗数量/需要数量）*100
                    let losstate = (Number(target.lossQuantity) / Number(target.requireQuantity)) * 100;
                    target.lossRate = losstate.toFixed(4);
                }

                //如果有辅计量换算率就计算辅计量的计划数量
                if (target.unitExchangeRate) {
                    //辅计量计划数量
                    target.subPlannedQuantity = (Number(target.plannedQuantity) / Number(target.unitExchangeRate)).toFixed(4);
                    //辅计量需要数量
                    target.subRequireQuantity = (Number(target.requireQuantity) / Number(target.unitExchangeRate)).toFixed(4);
                    //辅计量损耗数量
                    target.subLossQuantity = (Number(target.subPlannedQuantity) - Number(target.subRequireQuantity)).toFixed(4);
                }
            } else if (dataIndex == 'baseRequireQuantity') {
                if(target.bomId){
                    this.$message.warning("来自Bom的需求基数不能修改");
                    return;
                }
                this.$set(target, dataIndex, value);
                  //需要数量
                target.requireQuantity = (Number(value) * Number(this.dataSource[this.classWorkCurrent].baseQuantity)).toFixed(4);
                if(target.lossRate){
                    target.lossQuantity = (Number(target.requireQuantity) * Number(target.lossRate)).toFixed(4);
                }
                //计划数量
                target.plannedQuantity = (Number(target.lossQuantity) + Number(target.requireQuantity)).toFixed(4);
                //如果有辅计量换算率就计算辅计量的计划数量
                if (target.unitExchangeRate) {
                    //辅计量计划数量
                    target.subPlannedQuantity = (Number(target.plannedQuantity) / Number(target.unitExchangeRate)).toFixed(4);
                    //辅计量需要数量
                    target.subRequireQuantity = (Number(target.requireQuantity) / Number(target.unitExchangeRate)).toFixed(4);
                    //辅计量损耗数量
                    target.subLossQuantity = (Number(target.subPlannedQuantity) - Number(target.subRequireQuantity)).toFixed(4);
                }
            }
            else if (dataIndex == 'requireQuantity') {
                //需要数量
                this.$set(target, dataIndex, value);
            } else if (dataIndex == 'lossQuantity') {
                this.$set(target, dataIndex, value);
                //损耗数量 || 损耗率
                if (target.lossQuantity != null && target.requireQuantity != null) {
                    //计算  损耗率=（损耗数量/需要数量）*100
                    let losstate = (Number(target.lossQuantity) / Number(target.requireQuantity)) * 100;
                    target.lossRate = losstate.toFixed(4);
                }
                if (target.requireQuantity != null && target.lossQuantity != null) {
                    //计算 计划数量=需要数量+损耗数量
                    target.plannedQuantity = (Number(target.requireQuantity) + Number(target.lossQuantity)).toFixed(4);

                }

                //如果有辅计量换算率就计算辅计量的计划数量
                if (target.unitExchangeRate) {
                    //辅计量计划数量
                    target.subPlannedQuantity = (Number(target.plannedQuantity) / Number(target.unitExchangeRate)).toFixed(4);
                    //辅计量需要数量
                    target.subRequireQuantity = (Number(target.requireQuantity) / Number(target.unitExchangeRate)).toFixed(4);
                    //辅计量损耗数量
                    target.subLossQuantity = (Number(target.subPlannedQuantity) - Number(target.subRequireQuantity)).toFixed(4);
                }

            } else if (dataIndex == 'lossRate') {
                this.$set(target, dataIndex, value);
                //输入损耗率
                if (target.lossRate != null && target.requireQuantity != null) {
                    //计算  损耗数量=需要数量*损耗率/100
                    target.lossQuantity = ((Number(target.requireQuantity) * Number(target.lossRate)) / 100).toFixed(4);
                }
                if (target.requireQuantity != null && target.lossQuantity != null) {
                    //计算 计划数量=需要数量+损耗数量
                    target.plannedQuantity = (Number(target.requireQuantity) + Number(target.lossQuantity)).toFixed(4);
                }

                //如果有辅计量换算率就计算辅计量的计划数量
                if (target.unitExchangeRate) {
                    //辅计量计划数量
                    target.subPlannedQuantity = (Number(target.plannedQuantity) / Number(target.unitExchangeRate)).toFixed(4);
                    //辅计量需要数量
                    target.subRequireQuantity = (Number(target.requireQuantity) / Number(target.unitExchangeRate)).toFixed(4);
                    //辅计量损耗数量
                    target.subLossQuantity = (Number(target.subPlannedQuantity) - Number(target.subRequireQuantity)).toFixed(4);
                }
            } 
            
            
            else if (dataIndex == 'subUnitName') {
                target['subUnit'] = value.id;//辅计量
                target['subUnitName'] = value.name;//辅计量名称
                target['unitExchangeRate'] = value.unitExchangeRate;//换算率

                if (target.plannedQuantity && target.requireQuantity) {
                    //辅计量计划数量
                    target.subPlannedQuantity = (Number(target.plannedQuantity) / Number(target.unitExchangeRate)).toFixed(4);
                    console.log(target.plannedQuantity, target.unitExchangeRate, target.subPlannedQuantity);
                    //辅计量需要数量
                    target.subRequireQuantity = (Number(target.requireQuantity) / Number(target.unitExchangeRate)).toFixed(4);
                    //辅计量损耗数量
                    target.subLossQuantity = (Number(target.subPlannedQuantity) - Number(target.subRequireQuantity)).toFixed(4);
                }
            } else if (dataIndex == 'inventoryCode' || dataIndex == 'inventoryName') {
                clearValue(target);
                target['inventoryCode'] = value.inventoryCode;//物料编码
                target['inventoryId'] = value.id;//物料名称
                target['inventoryName'] = value.inventoryName;//物料名称
                target['inventorySpecification'] = value.inventorySpecification;//规格型号
                target['taxRate'] = value.taxRate ? value.taxRate : 0;//税率
                // target['price'] = value.latestCost ? value.latestCost : value.referenceCost ? value.referenceCost : '';//单价（最新成本or参考成本）
                target['inventoryCategoryName'] = value.inventoryCategoryName;//存货分类
                target['inventoryCategoryId'] = value.inventoryCategoryId;  //存货分类id
                target['commodityAttribute'] = value.commodityAttribute;    //存货商品属性
                target['baseRequireQuantity'] = 1;   //需求基数默认1
                target['lossQuantity'] = 0;   //损耗数量
                target['lossRate'] = 0;   //损耗率
                if(this.dataSource[this.classWorkCurrent].baseQuantity){
                    target['requireQuantity'] = this.dataSource[this.classWorkCurrent].baseQuantity * 1;
                    target['plannedQuantity'] = this.dataSource[this.classWorkCurrent].baseQuantity * 1;
                }
                

                if (value.unitType == '多计量') {
                    target['baseUnit'] = value.mainUnit;
                    target['baseUnitName'] = value.mainUnitName;
                    target['mainUnit'] = value.mainUnit;
                    target['unitGroupId'] = value.unitGroupId;
                } else {
                    target['baseUnit'] = value.unitId;
                    target['baseUnitName'] = value.unitName;
                    target['unitId'] = value.unitId;
                }

            } else {
                if (target) {
                    this.$set(target, dataIndex, value)
                }
            }

            this.$nextTick(() => {
                this.dataSourceBom = dataSourceBom;
                this.reloadWork();
            })
        },
        //工艺明细表单修改回调处理（工序）
        onCellChangeMinRoute (indexTable, dataIndex, value) {
            console.log(indexTable, dataIndex, value,);
            let dataSourceRoute = [];
            this.dataSource.forEach(item => {
                if (item.processRouteId == this.currentRouteId) {
                    dataSourceRoute = item.procedureDetails;
                }
            });

            const target = dataSourceRoute.find((item, index) => index === indexTable);


            if (dataIndex == 'workerName') {
                //工人姓名
                if (value) {
                    target['workerNames'] = value.name;
                    target['workerIds'] = value.id;
                } else {
                    target['workerNames'] = null;
                    target['workerIds'] = null;
                }
            } else if (dataIndex == 'teamName') {
                //班组
                if (value) {
                    target['teamName'] = value.name;
                    target['teamId'] = value.id;
                } else {
                    target['teamName'] = null;
                    target['teamId'] = null;
                }
            } else {
                if (target) {
                    this.$set(target, dataIndex, value)
                }
            }

            console.log(dataSourceRoute);
            this.$nextTick(() => {
                this.dataSource.forEach(item => {
                    if (item.id == this.currentRouteId) {
                        item.procedureDetails = dataSourceRoute;
                    }
                });
                this.reload();
            })
        },
        // 选计划订单
        choiceBillsFromProductionOrder () {
            let postData = {
                sourceCode: 'ProductionOrder',      // 来源单
                title: '选计划订单',
                businessType: 2, //1:退货业务 2：非退货业务 3: 退货 + 非退货 4: 发票
                someBusinessType: '0',    // 指定业务类型 默认 0
                startVoucherState: 0,
                endVoucherState: 10
            }
            this.$refs.searchList.onOpenBox(postData);
        },









        //--------------------------------------右键-----------------------------
        reloadWork () {
            this.isRouterAliveWork = false;
            this.$nextTick(function () {
                this.isRouterAliveWork = true;
            });
        },
        openMenuDetails (e) {
            //显示右键菜单
            var x = e.pageX - 250;
            var y = e.pageY - 40;
            this.topDetails = y;
            this.leftDetails = x;
            this.visibleDetails = true;
        },
        closeMenuDetails () {
            //隐藏右键菜单
            this.visibleDetails = false;
        },
        handleAddDetails () {
            //新增数据
            let data = [];
            data = this.dataSourceBom;
            const newData = {
                number: data.length,
            };
            this.$nextTick(() => {
                data.splice(data.length, 0, newData);
                document.getElementById('documents-wrapper').scroll(0, this.$refs.print.scrollHeight);

                this.dataSourceBom = data;

                this.reloadWork();
            })
        },
        handleDeleteDetails () {
            //删除整行
            let _this = this;
            let numberId = this.thisClickIdDetails;
            let data = [];
            data = this.dataSourceBom;
            this.$confirm({
                title: "确认",
                content: (
                    <span>
                        您确定要{<span style="color:red;">删除</span>}该记录吗？
                    </span>
                ),
                onOk () {
                    let dataSource = [...data];
                    if (dataSource.length - 1 > _this.dataSourceNumberOther) {
                        //大于规定行数(删除)
                        dataSource = dataSource.filter((item, index) => index !== numberId);
                    } else {
                        //小于规定行数(清空)
                        for (let i = 0; i < dataSource.length; i++) {
                            if (i === numberId) {
                                for (const key in dataSource[i]) {
                                    if (key != 'number') {
                                        dataSource[i][key] = null;
                                    }
                                }
                            }
                        }
                    }
                    _this.dataSourceBom = dataSource;
                    _this.reloadWork();
                },
                onCancel () { },
            });
        },
        onCellChangeTerms (indexTable, dataIndex, value) {
            let data = [];
            data = this.dataSourceBom;
            const dataSource = [...data];
            const target = dataSource.find((item, index) => index === indexTable);
            console.log(target, dataIndex, value, indexTable);
            this.$set(target, dataIndex, value)
            if (dataIndex == 'codeTerms' || dataIndex == 'nameTerms') {
                //工序编码
                if (value) {
                    target['name'] = value.name;
                    target['code'] = value.code;
                    target['content'] = value.content;
                    target['remarks'] = value.remarks;
                } else {
                    target['name'] = null;
                    target['code'] = null;
                    target['content'] = null;
                    target['remarks'] = null;
                }
            } else if (dataIndex == 'paymentType') {
                //结算类型
                target['type'] = value;
            } else if (dataIndex == 'fileUrl') {
                //合同附件
                target['fileName'] = value.fileName;
                target['fileUrl'] = value.fileUrl;
                target['fileType'] = value.fileType;
            }
            this.$nextTick(() => {
                this.dataSourceBom = dataSource;
                this.reloadWork();
            })
        },
        //--------------------------------------右键-----------------------------












    }
};
</script>
<style lang="less">
    @import '~@/style/purchase/voucher.less';
    .hoverWorkStyle {
        background-color: rgba(24, 144, 255, 0.2);
        td {
            color: #222;
        }
    }

    .wuliao-mask {
        z-index: 10;
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        right: 0;
        height: calc(100% - 20px);
        width: calc(100% - 20px);
        background: rgba(0, 0, 0, 0);
    }
</style>